package Net;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SocketChannel;


public class TcpConnection {
	private final int BUFFER_SIZE = 1024*64;
	private SocketChannel channel_;
	private ByteBuffer buffer_;
	private TcpServer server_;
	
	public TcpConnection(TcpServer server, SocketChannel channel)
	{
		channel_ = channel;
		buffer_ = ByteBuffer.allocate(BUFFER_SIZE);
		server_ = server;
	}
	
	public int onReadMessage() throws IOException
	{
		buffer_.clear();
		int len = channel_.read(buffer_);
		if (len == -1)
		{
			channel_.close();
			server_.connectionIsClose(channel_.toString());
		}
		return len;
	}
	
	public int onSendMessage(ByteBuffer buffer) throws IOException
	{
		int len = 0;
		try {
			len = channel_.write(buffer);
		} catch (NotYetConnectedException ntc) {
			// TODO Auto-generated catch block
			ntc.printStackTrace();
			server_.connectionIsClose(channel_.toString());
			
		} catch (ClosedChannelException  cc)
		{
			cc.printStackTrace();
			channel_.close();
			server_.connectionIsClose(channel_.toString());
		}
		return len;
	}
	
	public ByteBuffer getBuffer()
	{
		return buffer_;
	}
	
	public String getCid()
	{
		return channel_.toString();
	}
}
